package com.yq.netty.simple;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelPipeline;
import io.netty.util.CharsetUtil;

/**
 * @ClassName nettyServerHandler
 * @Description TODO
 * @Author yaoqiang
 * @Date 2021/6/10 15:50
 * @Version 1.0
 */
public class nettyServerHandler extends ChannelInboundHandlerAdapter {
    /**
     * women dingyige handler需要继续netty规定好的某个handlerAdapter
     我们可以在合理读取客户端发送的消息
     ChannelHandlerContext ctx 上下文镀锡量，含有关到pipeline 通道channel地址
     object msg 就是客户端发送的默认数据
     */

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("服务器读取线程"+Thread.currentThread().getName());
        System.out.println("server ctx="+ctx);
        System.out.println("查看channel和pipeline的关系");
        Channel channel = ctx.channel();
        //本质是一个双向链接，出栈入栈
        ChannelPipeline pipeline = ctx.pipeline();
//msg转成一个ByteBuf，ByteBuf是Netty提供的
        ByteBuf byteBuf = (ByteBuf) msg;
        System.out.println("客户端地址："+channel.remoteAddress()+"客户端发送的消息是："+byteBuf.toString(CharsetUtil.UTF_8));
    }

    /**
     * 数据读取完毕
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        //将数据写到缓存中并刷新，一般我们需要对这个数据进行编码
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello,客户端 ", CharsetUtil.UTF_8));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
